﻿//-----------------------------------------------------------------------
// <copyright company="www.3WayWebdesign.de">
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//
// <author>Michael Morbach</author>
// <email>Michael@3waywebdesign.de</email>
// <web>http://www.3waywebdesign.de</web>
//-----------------------------------------------------------------------

namespace Tww.Pixxler.PixxlerAPI.ServiceAPI
{
    #region Imports

    using Microsoft.Practices.Unity;
    using System;
    using Tww.Pixxler.PixxlerAPI.UserServiceReference;
    using Tww.Pixxler.PixxlerAppInfrastructure.Interfaces.API;
    using Tww.Pixxler.SharedObjects.DTO;


    #endregion

    public class UserAPI : IPixxlerUserAPI
    {
        public UserAPI( IUnityContainer unityContainer )
        {
            this.UnityContainer = unityContainer;
        }

        #region Private Properties

        protected IUnityContainer UnityContainer { get; set; }

        #endregion

        #region Public Properties

        public PixxlerUserDTO LoggedUser { get; private set; }

        public Guid SessionID { get; private set; }

        #endregion

        #region Private Methods

        protected virtual void RaiseUserLoggedOut()
        {
            var listener = this.UserLoggedOut;

            if ( listener != null )
            {
                listener( this, EventArgs.Empty );
            }
        }

        protected virtual void RaiseUserLoginSucceded()
        {
            var listener = this.UserLoginSucceded;

            if ( listener != null )
            {
                listener( this, EventArgs.Empty );
            }

        }

        protected virtual void RaiseUserLoginFailed( string errorMessage )
        {
            var listener = this.UserLoginFailed;

            if ( listener != null )
            {
                listener( this, new PixxlerAppInfrastructure.Events.EventArgs.LoginFailedEventArgs( errorMessage ) );
            }

        }

        #endregion

        #region Methods

        public void RequestLogin()
        {
            this.RaiseUserLoggedOut();
        }

        public void Login( string username, string password )
        {
            using ( var userService = new PixxlerUserServiceClient() )
            {
                try
                {
                    this.SessionID = userService.Login( username, password );
                }
                catch ( System.ServiceModel.EndpointNotFoundException ex )
                {
                    this.RaiseUserLoginFailed( "Es konnte keine Verbindung mit dem Service hergestellt werden" );
                    return;
                }
                catch ( System.ServiceModel.FaultException ex )
                {
                    this.RaiseUserLoginFailed( "Die Kommunikation mit dem Service ergab einen Fehler auf Seiten des Services" );
                    return;
                }

                if ( SessionID != Guid.Empty )
                {
                    this.LoggedUser = userService.GetUser( this.SessionID );

                    if ( this.LoggedUser != null )
                    {
                        this.RaiseUserLoginSucceded();
                    }
                }
                else
                {
                    this.RaiseUserLoginFailed( "Kombination aus Benutzername und Password wurde nicht aktzeptiert" );
                }
            }
        }

        public void Logout()
        {
            using ( var userService = new PixxlerUserServiceClient() )
            {
                userService.LogoutAsync( this.SessionID );
                this.RaiseUserLoggedOut();
            }
        }

        public bool IsUserAuthenticated()
        {
            using ( var userService = new PixxlerUserServiceClient() )
            {
                return this.LoggedUser != null && this.SessionID != Guid.Empty && userService.ValidateSession( this.SessionID );
            }
        }

        #endregion

        #region Events

        public event EventHandler UserLoggedOut;
        public event EventHandler UserLoginSucceded;
        public event EventHandler<PixxlerAppInfrastructure.Events.EventArgs.LoginFailedEventArgs> UserLoginFailed;

        #endregion




    }
}
